/* eslint-disable eqeqeq */
<template>
  <div class="menu-tree-container">
    <!-- <el-input style="margin-bottom:10px"
              placeholder="搜索分类"
              prefix-icon="el-icon-search"
              v-model="filterText"></el-input> -->
    <div style="overflow-y:auto;height:100%;">
      <el-tree class="treeShow"
               default-expand-all
               :data="menuTree"
               :props="defaultProps"
               label="menu_name"
               node-key="id"
               ref="menuList"
               :highlight-current="true"
               :filter-node-method="filterNode"
               :expand-on-click-node="true"
               @node-contextmenu="rihgtClick"
               @node-click="getId"
               :default-expanded-keys="selectedNodeList"
               :auto-expand-parent="false"
               draggable
               :accordion="false">
        <span class="slot-t-node"
              slot-scope="{ node, data }">
          <span v-show="!node.isEdit">
            <span v-show="data.children_list && data.children_list.length >= 1">
              <!-- <i :class="{'el-icon-time':node.level<=1,'el-icon-bell':node.level>1&&node.level<=2,'el-icon-service':node.level>2}" /> -->
              <i :class="{ 'el-icon-plus':!node.expanded,'el-icon-minus':node.expanded}" />
              <span :class="[data.id >= maxexpandId ? 'slot-t-node--label' : '']"
                    :title="data.system_name||data.menu_name||data.wbs_name">{{data.system_name || data.menu_name || data.wbs_name}}</span>
            </span>
            <!-- 当树形节点不存在子节点时，设置单独的图标 -->
            <span v-show="!data.children_list || data.children_list.length == 0">
              <i class="el-icon-document"></i>
              <span :class="[data.id >= maxexpandId ? 'slot-t-node--label' : '']"
                    :title="data.system_name||data.menu_name ||data.wbs_name">{{data.system_name || data.menu_name ||data.wbs_name}}</span>
            </span>
          </span>
          <!-- 编辑输入框 -->
          <span v-show="node.isEdit">
            <el-input class="slot-t-input"
                      size="mini"
                      autofocus
                      v-model="data.name"
                      :ref="'slotTreeInput'+data.id"
                      @blur.stop="NodeBlur(node, data)"
                      @keyup.enter.native="NodeBlur(node, data)"></el-input>
          </span>
        </span>
      </el-tree>
    </div>

    <!--鼠标右键点击出现页面-->
    <div v-show="menuVisible">
      <el-menu id="rightClickMenu"
               class="el-menu-vertical"
               @select="handleRightSelect"
               active-text-color="#fff"
               text-color="#fff">
        <!-- 根据不同的状态，显示不同的右键自定义菜单（岗位与非岗位状态） -->
        <!-- <el-menu-item index="7"
                      v-show="areaNodes=='2'&&nodeLevel===1?true:false"
                      class="menuItem">
          <i class="el-icon-plus"
             style="color:#fff" />
          <span slot="title">新增区域节点</span>
        </el-menu-item> -->
        <el-menu-item index="7"
                      v-show="(areaNodes=='2'&&nodeLevel<4)&&isProDesDecompPage==false?true:false"
                      class="menuItem">
          <i class="el-icon-plus"
             style="color:#fff" />
          <span slot="title">新增区域节点</span>
        </el-menu-item>
        <el-menu-item index="8"
                      v-show="(areaNodes=='2'&&nodeLevel>=2)&&isProDesDecompPage==false?true:false"
                      class="menuItem">
          <i class="el-icon-plus"
             style="color:#fff" />
          <span slot="title">楼号</span>
        </el-menu-item>
        <el-menu-item index="9"
                      v-show="areaNodes=='3'&&isProDesDecompPage==false?true:false"
                      class="menuItem">
          <i class="el-icon-plus"
             style="color:#fff" />
          <span slot="title">层号</span>
        </el-menu-item>
        <el-menu-item index="11"
                      v-show="areaNodes=='4'&&isProDesDecompPage==false?true:false"
                      class="menuItem">
          <i class="el-icon-plus"
             style="color:#fff" />
          <span slot="title">关联构件</span>
        </el-menu-item>
        <el-menu-item index="10"
                      v-if="isProDesignAndDecome==true"
                      v-auth="'modify-floors-button'"
                      class="menuItem">
          <i class="el-icon-edit"
             style="color:#fff" />
          <span slot="title">修改</span>
        </el-menu-item>
        <el-menu-item index="10"
                      v-else
                      class="menuItem">
          <i class="el-icon-edit"
             style="color:#fff" />
          <span slot="title">修改</span>
        </el-menu-item>
        <el-menu-item index="12"
                      v-if="isShowEditDesignInfo==true&&isProDesDecompPage==true&&this.areaNodes !== '4'"
                      v-auth="'modify-design-info-button'"
                      class="menuItem">
          {{this.projectForm.wbs_type}}
          <i class="el-icon-edit"
             style="color:#fff" />
          <span slot="title">编辑设计信息</span>
        </el-menu-item>
        <el-menu-item index="3"
                      v-if="isProDesignAndDecome==true"
                      v-auth="'floors-del-button'"
                      class="menuItem">
          <i class="el-icon-delete"
             style="color:#fff" />
          <span slot="title">删除</span>
        </el-menu-item>
        <el-menu-item index="3"
                      v-else
                      class="menuItem">
          <i class="el-icon-delete"
             style="color:#fff" />
          <span slot="title">删除</span>
        </el-menu-item>
      </el-menu>
    </div>
    <!-- 新增或修改子节点 -->
    <el-dialog :visible.sync="addSonUnitDialog"
               :close-on-click-modal="false"
               :title="judge==1?'新增菜单':'修改菜单'"
               width="45%">
      <el-form :model="sonUnitform"
               ref="editMenuForm"
               label-width="75px">
        <el-form-item label="菜单编号">
          <el-input v-model="sonUnitform.menu_no"
                    autocomplete="off"
                    class="col-6"
                    style="width:100%!important;"
                    placeholder="请输入菜单编号">
          </el-input>
        </el-form-item>
        <el-form-item label="菜单名称">
          <el-input v-model="sonUnitform.menu_name"
                    autocomplete="off"
                    class="col-6"
                    style="width:100%!important;"
                    placeholder="请输入菜单名称">
          </el-input>

        </el-form-item>
        <el-form-item label="菜单图标">
          <el-input v-model="sonUnitform.menu_css"
                    autocomplete="off"
                    class="col-6"
                    style="width:92%!important;"
                    placeholder="请输入菜单图标">
          </el-input>
          <i class="el-icon-share select-icon"
             @click="selectIconDialogVisible=true"></i>
        </el-form-item>
        <!-- <el-form-item label="前端路由">
          <el-input v-model="sonUnitform.route_url"
                    class="col-6"
                    placeholder="请输入前端路由">
          </el-input>
        </el-form-item> -->
      </el-form>
      <div style="text-align:center;">
        <el-button type="primary"
                   @click="addSonUnitDialog= false"
                   id="search-style">返 回</el-button>
        <el-button @click="addMenuTreeNode"
                   id="save-style">保 存</el-button>
      </div>
    </el-dialog>
    <!-- 添加区域节点弹窗 -->
    <el-dialog title="添加区域节点"
               :close-on-click-modal="false"
               :append-to-body='true'
               :visible.sync="addProjectDialog"
               width="30%">
      <el-form :model="projectForm"
               status-icon
               :rules="addRules"
               ref="projectForm"
               label-width="60px"
               class="demo-ruleForm">
        <el-form-item label="名称"
                      prop="wbs_name">
          <el-input type="text"
                    v-model="projectForm.wbs_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="clearAddProject('projectForm')">取 消</el-button>
        <el-button type="primary"
                   @click="sureAddProject('projectForm')">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改区域节点等弹窗 -->
    <el-dialog title="修改"
               :close-on-click-modal="false"
               :append-to-body='true'
               :visible.sync="editProjectDialog"
               width="30%">
      <el-form :model="editProjectForm"
               status-icon
               :rules="editRules"
               ref="editProjectForm"
               label-width="60px"
               class="demo-ruleForm">
        <el-form-item label="名称"
                      prop="wbs_name">
          <el-input v-model="editProjectForm.wbs_name"></el-input>
        </el-form-item>
        <el-form-item label="序号"
                      v-if='nodeShow==="4"'
                      prop="sort_no">
          <el-input type="text"
                    oninput="value=value.replace(/[^0-9.-]/g,'')"
                    v-model="editProjectForm.sort_no"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="clearEditProject('editProjectForm')">取 消</el-button>
        <el-button type="primary"
                   @click="sureEditProject('editProjectForm')">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加楼号弹窗 -->
    <el-dialog title="添加楼号"
               :close-on-click-modal="false"
               :append-to-body='true'
               :visible.sync="addBuildDialog"
               width="30%">
      <el-form :model="buildForm"
               status-icon
               :rules="buildRules"
               ref="buildForm"
               label-width="60px"
               class="demo-ruleForm">
        <el-form-item label="名称"
                      prop="wbs_name">
          <el-input v-model="buildForm.wbs_name"
                    placeholder="请输入名称"
                    :maxlength="32"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="clearBuildProject('buildForm')">取 消</el-button>
        <el-button type="primary"
                   @click="sureBuildProject('buildForm')">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加层号弹窗 -->
    <el-dialog title="添加层号"
               :close-on-click-modal="false"
               :append-to-body='true'
               :visible.sync="addFloorDialog"
               width="30%">
      <el-form :model="floorForm"
               status-icon
               :rules="floorRules"
               ref="floorForm"
               label-width="60px"
               class="demo-ruleForm">
        <el-form-item label="名称"
                      prop="wbs_name">
          <el-input type="text"
                    v-model="floorForm.wbs_name"></el-input>
        </el-form-item>
        <el-form-item label="序号"
                      prop="sort_no">
          <el-input type="text"
                    oninput="value=value.replace(/[^0-9.-]/g,'')"
                    v-model="floorForm.sort_no"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="clearFloorProject('floorForm')">取 消</el-button>
        <el-button type="primary"
                   @click="sureFloorProject('floorForm')">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 关联构件弹窗 -->
    <el-dialog title="关联构件"
               :close-on-click-modal="false"
               :append-to-body='true'
               :visible.sync="memberDialog"
               @open="getUnallocatedList"
               @close="clearUnallocatedList"
               width="50%">
      <el-row>
        <!-- :format="{
                              noChecked: '${total}',
                              hasChecked: '${checked}/${total}'
                            }" -->
        <el-col :span="24"
                align="center">
          <el-transfer style="text-align: left; display: inline-block"
                       class="transfer"
                       v-model="valueArr"
                       :filterable='false'
                       :left-default-checked="[]"
                       :right-default-checked="[]"
                       :render-content="renderFunc"
                       :titles="['已分配', '未分配']"
                       :button-texts="['添加', '移除']"
                       @change="handleChange"
                       :data="memberArr">
          </el-transfer>
        </el-col>
      </el-row>
    </el-dialog>
    <EditDesignInfoDialog v-if="designInfoVisible==true"
                          :objRow.sync="objRow"
                          :designInfoVisible.sync="designInfoVisible"></EditDesignInfoDialog>
    <!-- <FontAwesome :selectedIcon.sync="sonUnitform.menu_css"
                 :isVisible.sync="selectIconDialogVisible"></FontAwesome> -->
  </div>
</template>
<script>
import EditDesignInfoDialog from './components/EditDesignInfoDialog'
import { menuManageApi } from '@/services/SystemSetting'
// import { projectTreedApi } from '@/services/ProjectCenter'
import { projectDecomApi, ProDesignDecomApi } from '@/services/ProjectCenter'
import FontAwesome from '@/components/FontAwesome/FontAwesome'
// import api from '../../resource/api.js'

export default {
  name: 'leftTree',
  data () {
    var checkName = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入名称'))
      } else {
        callback()
      }
    }
    var checkEditName = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入名称'))
      } else {
        callback()
      }
    };
    var checkEditSortNo = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入序号'));
      } else if (!(/^-?\d+$|^-?\d*\.\d+$/g).test(value)) {
        callback(new Error('请输入正确的序号'));
      } else {
        callback();
      }
    };
    var checkBuildName = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入楼号'))
      } else {
        callback()
      }
    }
    var checkFloorName = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入名称'));
      } else {
        callback();
      }
    };
    var checkSortNo = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入序号'));
      }
      else if (!(/^-?\d+$|^-?\d*\.\d+$/g).test(value)) {
        callback(new Error('请输入正确的序号'));
      }
      else {
        callback();
      }
    };
    // const generateData = _ => {
    //   const data = [];
    //   for (let i = 1; i <= 15; i++) {
    //     data.push({
    //       key: i,
    //       label: `备选项 ${i}`,
    //     });
    //   }
    //   return data;
    // };
    return {
      isProDesignAndDecome: false,//false：非项目设计与分解页面；true:项目设计与分解页面
      objRow: {},
      wbsId: 0,
      designInfoVisible: false,//设计信息
      addProjectDialog: false, // 添加区域节点、楼号等弹窗
      addRules: {// 添加单项工程表单规则
        wbs_name: [
          { required: true, validator: checkName, trigger: 'blur' }
        ]
      },
      editProjectDialog: false, // 修改区域节点弹窗
      editRules: {// 添加单项工程表单规则
        wbs_name: [
          { required: true, validator: checkEditName, trigger: 'blur' }
        ],
        sort_no: [
          { required: true, validator: checkEditSortNo, trigger: 'blur' }
        ]
      },
      addBuildDialog: false, // 添加楼号弹窗
      buildRules: {
        wbs_name: [
          { required: true, validator: checkBuildName, trigger: 'blur' }
        ]
      },
      addFloorDialog: false, // 添加层号弹窗
      floorRules: {
        wbs_name: [
          { required: true, validator: checkFloorName, trigger: 'blur' }
        ],
        sort_no: [
          { required: true, validator: checkSortNo, trigger: 'blur' }
        ]
      },
      judge: '',
      info: this.messageinfo,
      work: false,
      filterText: '',
      addSonUnitDialog: false,
      addDepDialog: false,
      addJobDialog: false,
      memberDialog: false, // 关联构件弹窗
      memberArr: [],
      // data: this.memberArr,
      valueArr: [],
      renderFunc (h, option) {
        return <span>{option.label}</span>
      },
      DATA: null,
      NODE: null,
      maxexpandId: 95, // 新增节点开始id
      non_maxexpandId: 95, // 新增节点开始id(不更改)
      isLoadingTree: true, // 是否加载节点树
      //   setTree:api.treelist,//节点树数据
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      menuVisible: false,
      objectID: null,
      // 子单位
      sonUnitform: {
        menu_name: '',
        menu_no: '',
        menu_id: '',
        p_menu_no: '',
        menu_css: '',
        route_url: ''
      },
      // 新增区域节点
      projectForm: {
        project_id: '',
        wbs_type: '',
        wbs_id: '',
        p_wbs_no: '',
        wbs_name: ''
      },
      // 修改区域节点
      editProjectForm: {
        project_id: "",
        wbs_type: "",
        wbs_id: "",
        wbs_name: "",
        sort_no: ""
      },
      // 新增楼号
      buildForm: {
        project_id: '',
        wbs_type: '',
        wbs_id: '',
        p_wbs_no: '',
        wbs_name: ''
      },
      // 新增层号
      floorForm: {
        project_id: "",
        wbs_type: "",
        wbs_id: "",
        p_wbs_no: "",
        wbs_name: "",
        sort_no: ""
      },
      // 关联构件
      memberForm: {
        project_id: '',
        wbs_id: ''
      },
      // 编辑或新增
      addOrEdit: 'add',
      menuTreeParam: {
        menu_no: '0'
      },
      // 需要删除的菜单数据
      deleteProjectTreeParam: {
        wbs_id: ''
        // menu_no: ''
      },
      // 选择图标弹框是否可见
      selectIconDialogVisible: false,
      // 选中的节点列表，用于刷新后展开到指定位置
      selectedNodeList: [],
      areaNodes: '',
      requestParams: {
        project_id: ''
      },
      nodeLevel: 1,
      nodeShow: '0',
      nodeCount: 0
    }
  },
  props: {
    isProDesDecompPage: {
      type: Boolean,
      default: () => {
        return false
      }
    },
    curMenu: Object,
    isShowEditDesignInfo: {
      type: Boolean,
      default: () => {
        return false
      }
    }
  },
  components: {
    FontAwesome,
    EditDesignInfoDialog,//设计信息
  },
  methods: {
    getResTree () {//项目设计与分解-查看wbs树形结构
      ProDesignDecomApi.getResTree({
        params: {
          project_id: this.requestParams.project_id || '1',//项目主键值
        }
      }).then((res) => {
        if (res.data) {
          this.commonMenuTreeData(res);//通用-获取wbs树数据
        }
        console.log('当前项目下的wbs树形数据res=', res)
      }).catch((error) => {
        console.log(error)
      })
    },
    // 层值改变时触发的事件
    keyupBuildChange (val) {
      if (val == 0) {
        this.editProjectForm.wbs_name = ''
      }
      // if (val == '-') {
      //   this.editProjectForm.wbs_name = '';
      // }
      this.editProjectForm.wbs_name = this.editProjectForm.wbs_name.replace(/\-{2,}/g, '-') // 只保留第一个. 清除多余的
      this.editProjectForm.wbs_name = this.editProjectForm.wbs_name.replace(/[^(\-)0-9]/g, '') // 清除“数字”和“.”以外的字符

      console.log('层', val)
    },

    // 新增
    onAdd () {
      this.judge = 1
    },
    onEdit () {
      this.judge = 2
    },
    // 节点点击事件获取id
    getId (data, node) {
      if (data.wbs_id) {
        this.$emit('ids', data)
      }
      if (data.project_id) {
        this.$emit('update:curId', 0)
        this.$emit('update:curId', data.project_id)
      }
      let curData = JSON.parse(JSON.stringify(data))
      this.menuVisible = false
      if (curData.is_dir === '1') {
        this.$emit('update:curMenu', curData)
      }
      if ((node.expanded || node.childNodes.length === 0) && data.id) {
        this.addNodeList(data.id)
      } else {
        this.removeNodeList(data.id)
      }
    },
    // 当当前节点是展开操作时,将当前节点的object_id添加到selectedNodeList中，为了刷新数据后能够展开到指定位置
    addNodeList (menuId) {
      let index = this.selectedNodeList.indexOf(menuId)
      if (index < 0) {
        this.selectedNodeList.push(menuId)
      }
      console.log('11', this.selectedNodeList)
    },
    // 当前节点是收起操作时，将当前节点的object_id从selectedNodeList中移除
    removeNodeList (menuId) {
      let index = this.selectedNodeList.indexOf(menuId)
      if (index >= 0) {
        this.selectedNodeList.splice(index, 1)
      }
      console.log('22', this.selectedNodeList)
    },
    // 对树节点进行筛选时执行的方法，返回 true 表示这个节点可以显示，返回 false 则表示这个节点会被隐藏
    filterNode (value, data) {
      // console.log('value:', value)
      // console.log('data:', data)
      if (!value) return true
      return data.menu_name.indexOf(value) !== -1
    },
    // 右键弹出的菜单点击事件
    handleRightSelect (key) {
      if (key == 1) {
        this.NodeAdd(this.NODE, this.DATA)
        this.menuVisible = false // 关闭右键打开的操作菜单
      } else if (key == 2) {
        this.NodeEdit(this.NODE, this.DATA)
        this.menuVisible = false
      } else if (key == 3) {
        this.NodeDel(this.NODE, this.DATA)
        this.menuVisible = false
      } else if (key == 4) {
        this.menuVisible = false
        this.addSonUnitDialog = true
      } else if (key == 5) {
        this.menuVisible = false
        this.addDepDialog = true
      } else if (key == 6) {
        this.menuVisible = false
        this.addJobDialog = true
      } else if (key == 7) {
        this.menuVisible = false
        this.ProjectNode(this.NODE, this.DATA)
        this.addProjectDialog = true
      } else if (key == 8) {
        this.menuVisible = false
        this.addBuildNode(this.NODE, this.DATA)
        this.addBuildDialog = true
      } else if (key == 9) {
        this.menuVisible = false
        this.addFloorNode(this.NODE, this.DATA)
        this.addFloorDialog = true
      } else if (key == 10) {
        this.menuVisible = false
        this.editProjectNode(this.NODE, this.DATA)
        this.editProjectDialog = true
        this.nodeShow = this.DATA.wbs_type;
      } else if (key == 11) {
        this.menuVisible = false
        this.addMemberNode(this.NODE, this.DATA)
        this.memberDialog = true
      } else if (key == 12) {//编辑设计信息
        this.menuVisible = false
        this.objRow = this.DATA;
        console.log(this.NODE, this.DATA)
        this.designInfoVisible = true;
      }
    },
    NodeBlur (n, d) {
      // 输入框失焦
      if (n.isEdit) {
        this.$set(n, 'isEdit', false)
      }
      this.$nextTick(() => {
        this.$refs['slotTreeInput' + d.id].$refs.input.focus()
      })
    },
    NodeEdit (n, d) {
      // console.log(n, d)
      let data = JSON.parse(JSON.stringify(d))
      this.addOrEdit = 'edit'
      this.judge = 2
      this.addSonUnitDialog = true
      this.sonUnitform.menu_name = data.menu_name
      this.sonUnitform.menu_no = data.menu_no
      this.sonUnitform.p_menu_no = data.p_menu_no
      // this.sonUnitform.system_no = data.system_no;
      this.sonUnitform.route_url = data.route_url
      this.sonUnitform.menu_css = data.menu_css
      this.sonUnitform.menu_id = data.menu_id
      // 编辑节点
      // if (!n.isEdit) {
      //   //检测isEdit是否存在or是否为false
      //   this.$set(n, "isEdit", true);
      // }
    },
    NodeDel (n, d) {
      // 删除节点
      console.log(d, 'delete tree')
      if (d.children && d.children.length !== 0) {
        this.$message.error('此菜单有子菜单，不可删除！')
        return false
      } else {
        // 新增节点可直接删除，已存在的节点要二次确认
        // 删除操作
        let DelFun = () => {
          let _list = n.parent.data.children || n.parent.data // 节点同级数据
          let _index = _list.map(c => c.id).indexOf(d.id)
          _list.splice(_index, 1)
          this.$message.success('删除成功！')
        }
        // 二次确认
        let ConfirmFun = () => {
          this.$confirm('是否删除此菜单？', '提示', {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning'
          })
            .then(() => {
              if (this.isProDesDecompPage == false) {
                this.deleteProjectTreeParam.wbs_id = d.wbs_id
                this.deleteMenuTreeNode()
              } else {
                this.deleteProjectTreeParam.wbs_id = d.resolve_wbs_id
                this.delResolveLayer();//项目设计与分解页面-楼层删除
              }
              this.$emit('update:curId', 0)
              this.$emit('update:curId', data.project_id)
            })
            .catch(() => { })
        }
        // 判断是否是新增节点
        d.id > this.non_maxexpandId ? ConfirmFun() : ConfirmFun()
        // d.id > this.non_maxexpandId ? DelFun() : ConfirmFun()
      }
    },
    delResolveLayer () {//删除节点
      ProDesignDecomApi.delResolve({
        data: {
          resolve_wbs_id: this.deleteProjectTreeParam.wbs_id
        }
      }).then((res) => {
        if (res.data) {
          if (res.code === 0) {
            this.$message.success('删除菜单成功')
            ++this.nodeCount
            this.getResTree();//数据刷新
            this.$store.dispatch('SetNodeCount', this.nodeCount)
            window.localStorage.setItem('SetNodeCount', this.nodeCount)
          }
        }
      }).catch((err) => {
        console.log(err)
      })
    },
    NodeAdd (n, d) {
      // 新增节点
      // console.log(n, d, 'add node')
      this.addOrEdit = 'add'
      this.sonUnitform = {}
      this.judge = 1
      this.sonUnitform.p_menu_no = d.menu_no
      // this.sonUnitform.system_no = d.system_no
      this.addSonUnitDialog = true
      // 判断层级
      // if (n.level >= 3) {
      //   this.$message.error("最多只支持三级！");
      //   return false;
      // }
    },
    // 打开新增区域节点
    ProjectNode (n, d) {
      console.log('n===>', n, d)
      this.projectForm.project_id = d.project_id
      this.projectForm.wbs_type = d.wbs_type
      this.projectForm.wbs_id = d.wbs_id
      this.projectForm.p_wbs_no = d.wbs_no
    },
    // 关闭新增区域节点弹窗
    clearAddProject (projectForm) {
      this.$refs[projectForm].resetFields()
      this.addProjectDialog = false
    },
    // 确认添加区域节点弹窗
    sureAddProject (projectForm) {
      this.$refs[projectForm].validate((valid) => {
        if (valid) {
          projectDecomApi.addOneProject({
            data: {
              project_id: this.projectForm.project_id,
              wbs_type: this.projectForm.wbs_type,
              wbs_id: this.projectForm.wbs_id,
              p_wbs_no: this.projectForm.p_wbs_no,
              wbs_name: this.projectForm.wbs_name
            }
          }).then(res => {
            if (res.code === 0) {
              this.getMenuTreeData()
              console.log('33', this.selectedNodeList)
              this.addProjectDialog = false
              this.$message.success('添加成功')
              this.$refs[projectForm].resetFields()
              this.$emit('update:curId', 0)
              this.$emit('update:curId', data.project_id)
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 打开修改区域节点
    editProjectNode (n, d) {
      this.editProjectForm.project_id = d.project_id;
      this.editProjectForm.wbs_type = d.wbs_type;
      this.editProjectForm.wbs_id = this.isProDesDecompPage == false ? d.wbs_id : d.resolve_wbs_id;
      this.editProjectForm.wbs_name = d.wbs_name;
      this.editProjectForm.sort_no = d.sort_no;
    },
    // 关闭修改区域节点弹窗
    clearEditProject (editProjectForm) {
      this.editProjectDialog = false
    },
    getEditLayerParams () {//获取项目设计与分解页面-楼层的修改传参
      let obj = {
        resolve_wbs_id: this.editProjectForm.wbs_id,
        wbs_name: this.editProjectForm.wbs_name,
        sort_no: this.editProjectForm.sort_no
      };
      return obj;
    },
    //项目设计与分解页面-左边树-楼层的修改方法
    editLayer () {
      ProDesignDecomApi.editResolve({
        data: this.getEditLayerParams()
      }).then((res) => {
        if (res.code == 0) {
          ++this.nodeCount;
          this.getResTree();//数据刷新
          this.$store.dispatch('SetNodeCount', this.nodeCount)
          window.localStorage.setItem('SetNodeCount', this.nodeCount)
          this.$message.success('修改成功')
          this.editProjectDialog = false
        };
      }).catch((error) => {
        console.log(error)
      })
    },
    proDecomEditLayer () {//项目分解页面-左边树-楼层的修改方法
      projectDecomApi.editProjectNode({
        data: {
          project_id: this.editProjectForm.project_id,
          wbs_type: this.editProjectForm.wbs_type,
          wbs_id: this.editProjectForm.wbs_id,
          wbs_name: this.editProjectForm.wbs_name,
          sort_no: this.editProjectForm.sort_no
        }
      }).then(res => {
        if (res.code === 0) {
          this.getMenuTreeData();//刷新
          this.editProjectDialog = false
          this.$message.success('修改成功')
        }
      })
    },
    // 确认修改区域节点弹窗
    sureEditProject (editProjectForm) {
      if (this.nodeShow === '4') {
        this.$refs[editProjectForm].validate((valid) => {
          if (valid) {
            if (this.isProDesDecompPage == true) {
              this.editLayer();//项目设计与分解页面-左边树-楼层的修改方法
            } else {
              this.proDecomEditLayer();//项目分解页面-左边树-楼层的修改方法
            }
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      } else {
        this.$refs[editProjectForm].validate((valid) => {
          if (valid) {
            if (this.isProDesDecompPage == true) {
              this.editLayer();//项目设计与分解页面-左边树-楼层的修改方法
            } else {
              projectDecomApi.editProjectNode({
                data: {
                  project_id: this.editProjectForm.project_id,
                  wbs_type: this.editProjectForm.wbs_type,
                  wbs_id: this.editProjectForm.wbs_id,
                  wbs_name: this.editProjectForm.wbs_name
                }
              }).then(res => {
                if (res.code === 0) {
                  this.getMenuTreeData()
                  this.editProjectDialog = false
                  this.$message.success('修改成功')
                }
              })
            }
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      }

    },
    // 打开添加楼号弹窗
    addBuildNode (n, d) {
      this.buildForm.project_id = d.project_id
      // this.buildForm.wbs_type = d.wbs_type
      this.buildForm.wbs_id = d.wbs_id
      this.buildForm.p_wbs_no = d.wbs_no
    },
    // 关闭添加楼号弹窗
    clearBuildProject (buildForm) {
      this.$refs[buildForm].resetFields()
      this.addBuildDialog = false
    },
    // 确认添加楼号弹窗
    sureBuildProject (buildForm) {
      this.$refs[buildForm].validate((valid) => {
        if (valid) {
          projectDecomApi.addOneProject({
            data: {
              project_id: this.buildForm.project_id,
              wbs_type: '3',
              wbs_id: this.buildForm.wbs_id,
              p_wbs_no: this.buildForm.p_wbs_no,
              wbs_name: this.buildForm.wbs_name
            }
          }).then(res => {
            if (res.code === 0) {
              this.getMenuTreeData()
              this.addBuildDialog = false
              this.$message.success('添加成功')
              this.$refs[buildForm].resetFields()
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 打开层号弹窗
    addFloorNode (n, d) {
      this.floorForm.project_id = d.project_id
      this.floorForm.wbs_id = d.wbs_id
      this.floorForm.p_wbs_no = d.wbs_no
    },
    // 取消添加层号弹窗
    clearFloorProject (floorForm) {
      this.$refs[floorForm].resetFields()
      this.addFloorDialog = false
    },
    // 确认添加层号弹窗
    sureFloorProject (floorForm) {
      this.$refs[floorForm].validate((valid) => {
        if (valid) {
          projectDecomApi.addOneProject({
            data: {
              project_id: this.floorForm.project_id,
              wbs_type: '4',
              wbs_id: this.floorForm.wbs_id,
              p_wbs_no: this.floorForm.p_wbs_no,
              wbs_name: this.floorForm.wbs_name,
              sort_no: this.floorForm.sort_no
            }
          }).then(res => {
            if (res.code === 0) {
              this.getMenuTreeData()
              this.addFloorDialog = false
              this.$message.success('添加成功')
              this.$refs[floorForm].resetFields();
              ++this.nodeCount
              this.$store.dispatch('SetNodeCount', this.nodeCount)
              window.localStorage.setItem('SetNodeCount', this.nodeCount)
              this.$refs[floorForm].resetFields()
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 右键点击事件
    rihgtClick (event, object, value, element) {
      // if (this.objectID !== object.menu_id) {
      //   this.objectID = object.menu_id;
      //   this.menuVisible = true;
      //   this.DATA = object;
      //   this.NODE = value;
      // } else {
      //   this.menuVisible = !this.menuVisible;
      // }
      this.DATA = object
      this.areaNodes = object.wbs_type
      this.nodeLevel = value.level
      // console.log('this.areaNodes', this.nodeLevel)
      this.NODE = value
      this.menuVisible = !this.menuVisible
      document.addEventListener('click', e => {
        this.menuVisible = false
      })
      console.log(object, value, '1111')
      let menu = document.querySelector('#rightClickMenu')
      let content = document.querySelector('.content-container')
      /* 菜单定位基于鼠标点击位置 */
      menu.style.left = event.clientX + 20 - 200 + 'px'
      menu.style.top = event.clientY - 220 + content.scrollTop + 'px'
      // console.log(event.clientY, content.scrollTop)
      menu.style.position = 'absolute' // 为新创建的DIV指定绝对定位
      menu.style.width = 160 + 'px'
    },
    // 处理传入的数据，因为后端都是children_list，需要手动赋值一个children字段
    handelData (arr) {
      if (Object.prototype.toString.call(arr) === '[object Array]') {
        arr.map((item) => {
          if (item.children_list) {
            item.children = item.children_list
            this.handelData(item.children_list)
          } else if (item.childrens) {
            item.children = item.childrens
            this.handelData(item.childrens)
          } else if (item.children) {
            item.children = item.children
            this.handelData(item.children)
            this.$nextTick(() => {
              item.id = String(item.wbs_id) || String(item.resolve_wbs_id);
            })
          } else {
            this.$nextTick(() => {
              item.id = String(item.wbs_id) || String(item.resolve_wbs_id);
            })
          }
          if (item.project) {
            item.id = item.project
          }
          if (!item.wbs_id) {
            item.wbs_id = '0'
          }
          if (!item.wbs_no) {
            item.wbs_no = '0'
          }
          if (!item.p_wbs_no) {
            item.p_wbs_no = '0'
          }
          if (!item.wbs_type) {
            item.wbs_type = '2'
          }
          if (item.sid) {
            item.menu_id = item.sid
          }
          if (item.menu_id === '') {
            item.menu_id = '0'
          }
        })
        return arr
      }
    },
    // 调用权限项分类新增或编辑接口
    addMenuTreeNode () {
      let msg = this.addOrEdit === 'add' ? '新增' : '修改'
      if (this.addOrEdit === 'add') {
        menuManageApi.createMenuTreeClass({
          data: this.sonUnitform
        }).then(res => {
          if (res.code === 0) {
            this.$message.success(msg + '菜单成功')
            this.$refs.editMenuForm.resetFields()
            this.addSonUnitDialog = false
            this.getMenuTreeData()
            this.$emit('update:curId', 0)
            this.$emit('update:curId', data.project_id)
          }
        })
      } else {
        menuManageApi.updateMenuTreeClass({
          data: this.sonUnitform
        }).then(res => {
          if (res.code === 0) {
            this.$message.success(msg + '菜单成功')
            this.addSonUnitDialog = false
            this.$refs.editMenuForm.resetFields()
            this.getMenuTreeData()
            this.$emit('update:curId', 0)
            this.$emit('update:curId', data.project_id)
          }
        })
      }
    },
    // 删除菜单分类
    deleteMenuTreeNode () {
      projectDecomApi.deleteProjectNode({
        data: this.deleteProjectTreeParam
      }).then(res => {
        if (res.code === 0) {
          this.$message.success('删除菜单成功')
          this.getMenuTreeData()
          ++this.nodeCount
          this.$store.dispatch('SetNodeCount', this.nodeCount)
          window.localStorage.setItem('SetNodeCount', this.nodeCount)
        }
      })
    },
    commonMenuTreeData (res) {//通用-获取wbs树数据
      this.wbsId = 0;//重置
      let menuTreData = res.data;//menuTreeData
      menuTreData = res.data;
      menuTreData.map((item) => {
        item.wbs_name = item.project
      });
      this.menuTreeData = menuTreData;
      console.log('true-menuTreeData=', this.menuTreeData)
      if (this.menuTreeData.length > 0) {
        var i = 0;
        this.menuTreeData.forEach(ele => {
          i = i + 1;
          this.$set(ele, 'id', i + 'j')
        });
        this.currentNodekey = this.menuTreeData[0].id
        this.selectedNodeList.push(this.menuTreeData[0].id)
        this.$refs.menuList.setCurrentKey(this.currentNodekey)// 一定要加这个选中了否则样式没有出来
        this.$emit('update:curId', this.menuTreeData[0].project_id)// 默认右边的图片数据展示
      }
      this.$store.dispatch('setDecomTree', this.menuTreeData)
      window.localStorage.setItem('decomTree', JSON.stringify(this.menuTreeData))
    },
    // 获取菜单树数据
    getMenuTreeData () {
      projectDecomApi.getTreeData({
        params: {
          project_id: this.requestParams.project_id || '1'
        }
      }).then(res => {
        if (res.data) {
          this.commonMenuTreeData(res);//通用-获取wbs树数据
        };
      })
    },
    // 打开关联构件弹窗
    addMemberNode (n, d) {
      this.memberForm.project_id = d.project_id
      this.memberForm.wbs_id = d.wbs_id
    },
    // 获取所有未分配与分配的构件列表
    getUnallocatedList () {
      projectDecomApi.getUnallocatedList({
        params: this.memberForm
      }).then(res => {
        var leftA = []
        for (var i = 0; i < res.data.length; i++) {
          if (res.data[i].type == '2') {
            leftA.push(i)
          }
          this.valueArr = leftA
          this.memberArr.push({
            key: i,
            label: res.data[i].cp_num
          })
        }
      })
    },
    // 清除数组
    clearUnallocatedList () {
      this.memberArr.splice(0, this.memberArr.length)
      // this.valueArr.splice(0, this.valueArr.length)
    },
    // 穿梭框
    handleChange (value, direction, movedKeys) {
      var changeArr = []
      if (direction === 'left') {
        for (var i = 0; i < movedKeys.length; i++) {
          changeArr.push(this.memberArr[movedKeys[i]].label)
        }
        projectDecomApi.addMember({
          data: {
            cp_num: changeArr.join(','),
            project_id: this.memberForm.project_id,
            wbs_id: this.memberForm.wbs_id
          }
        }).then(res => {
          if (res.code === 0) {
            this.$message.success('添加成功')
          }
        })
      } else {
        for (var i = 0; i < movedKeys.length; i++) {
          changeArr.push(this.memberArr[movedKeys[i]].label)
        }
        projectDecomApi.removeMember({
          data: {
            cp_num: changeArr.join(','),
            project_id: this.memberForm.project_id
          }
        }).then(res => {
          if (res.code === 0) {
            this.$message.success('移除成功')
          }
        })
      }
    },
    getIsProDesignAndDecome () {//判断当前页面是否为项目设计与分解页面
      let judge = false;
      let isProDesignAndDecome = window.location.href;
      if (isProDesignAndDecome.indexOf('/projectDesignAndDecompose') != -1) {
        judge = true;
      };
      return judge;
    }
  },
  watch: {
    isProDesDecompPage (n, o) {
      console.log('w-isProDesDecompPage=', n)
    },
    filterText (val) {
      this.$refs.menuList.filter(val)
    },
    messageinfo (newValue, oldValue) {
      this.info = newValue
    },
    getProjectInfo (newVal, oldVal) {
      console.log('newVal', newVal, oldVal)
      if (this.isProDesDecompPage == false) {
        this.getMenuTreeData()
      } else {
        this.getResTree();
      }

    }
  },
  computed: {
    menuTree () {
      let store = this.$store.state.decomTree
      let storage = JSON.parse(window.localStorage.getItem('decomTree'))
      // console.log('storage', storage, window.localStorage.getItem('decomTree'))
      let treeData = store.length > 0 ? store : storage
      treeData = this.handelData(treeData)
      return treeData
    },
    getProjectInfo () {
      let stateArray = this.$store.state.projectIdList
      let localArray = JSON.parse(window.localStorage.getItem('projectIdList'))
      let projectArray = !stateArray ? localArray : stateArray
      this.requestParams.project_id = projectArray.join(',')
      return this.requestParams.project_id
    }
  },
  async created () {
    this.isProDesignAndDecome = this.getIsProDesignAndDecome();//判断当前页面是否为项目设计与分解页面
    this.selectedNodeList = [];
    let store = this.$store.state.projectIdList;
    let storage = window.localStorage.getItem('projectIdList') || '[]'
    let projectIdList = []
    projectIdList = store.length > 0 ? store : JSON.parse(storage)
    let id = projectIdList || [1]
    this.requestParams.project_id = id.join(',')
    if (projectIdList) {
      if (this.isProDesDecompPage == false) {
        Promise.all([
          this.getMenuTreeData()
        ]).then(res => {
        })
      } else {
        Promise.all([
          this.getResTree()//项目设计与分解页面的接口
        ]).then(res => {
        })
      }
    }
  },
  mounted () {
  }
}
</script>
<style lang="scss" scoped>
#search-style {
  background: rgba(26, 188, 156, 1);
}
#save-style {
  color: white;
  background: rgba(26, 188, 156, 1);
}
/* 去掉默认的树形图标 */
/* .treeShow /deep/ .el-tree-node__content>.el-tree-node__expand-icon {
  display: none;
} */

.popover-new {
  /* position: absolute!important;
    right: 0;
    bottom: 0; */
}
/*顶部按钮*/
.slot-tree .slot-t-top {
  margin-bottom: 15px;
}
.slot-tree .slot-t-node span {
  display: inline-block;
}
/*节点*/
.slot-tree .slot-t-node--label {
  font-weight: 600;
}
/*输入框*/
.slot-tree .slot-t-input .el-input__inner {
  // height: 26px;
  // line-height: 26px;
}
/*按钮列表*/
.slot-tree .slot-t-node .slot-t-icons {
  display: none;
  margin-left: 10px;
}
.slot-tree .slot-t-icons .el-button + .el-button {
  margin-left: 6px;
}
.slot-tree .el-tree-node__content:hover .slot-t-icons {
  display: inline-block;
}
.menu-tree-container {
  z-index: 9999;
  width: 200px;
  min-height: 260px;
  height: auto;
  .select-icon {
    font-size: 30px;
    margin-left: 5px;
    transform: translateY(5px);
  }
  .menuItem {
    height: 40px;
    line-height: 40px;
    // background-color: #545c64;
    background-color: #f5f7fa;
    font-size: 14px;
  }
  /deep/ .menuItem i {
    color: #606266 !important;
  }
  /deep/ .menuItem span {
    color: #606266 !important;
  }
  .menuItem:hover {
    background-color: #409eff;
  }
  /deep/ .menuItem:hover i {
    color: #fff !important;
  }

  /deep/ .menuItem:hover span {
    color: #fff !important;
  }
  .el-tree {
    min-height: 260px;
    height: auto;
    max-height: 500px;
  }
}

/*************************标签鼠标右击页面样式******************************/
.el-menu-vertical {
  // border: 3px solid rgb(84, 92, 100);
  border-radius: 10px;
  z-index: 100;
  border: 2px solid #f5f7fa;
}
.el-menu-vertical i {
  color: #777777;
}

.add_tips /deep/ .el-form-item__label {
  padding-left: 28px;
}
.transfer {
  /deep/ .el-checkbox {
    margin-right: 60px;
  }
}
</style>
